package com.example.hospital.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.hospital.db.pojo.LoginInfoEntity;
import com.example.hospital.service.LoginInfoService;
import com.example.hospital.service.LoginService;
import com.example.hospital.service.MisUserService;
import com.example.hospital.utils.ip.IpUtils;
import org.springframework.stereotype.Service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hospital.utils.encipher.EncipherPwdUtils;
import com.example.hospital.db.pojo.MisUserEntity;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service("MisLoginService")
public class LoginServiceImpl implements LoginService {
  
  @Resource
  private MisUserService userService;
  @Resource
  private LoginInfoService loginInfoService;
  
  @Override
  public HashMap <String, Object> login(String username, String password) {
    String encipherPassword = EncipherPwdUtils.encipherPassword(password);
    System.out.println(encipherPassword);
    QueryWrapper <MisUserEntity> queryWrapper = new QueryWrapper <>();
    queryWrapper.eq("username", username);
    queryWrapper.eq("password", encipherPassword);
    MisUserEntity user = userService.getOne(queryWrapper);// 调用 getOne 方法
    HashMap <String, Object> result = new HashMap <>() {{
      put("isLogin", false);
    }};
    if(user != null && user.getId() != null) {
      Integer userId = user.getId();
      //      StpUtil.logout(userId); // 先退出，再登录，避免redis中含有多个userid对应的token
      StpUtil.login(userId);
      String token = StpUtil.getTokenValue();
      List <String> permissions = StpUtil.getPermissionList();
      result = new HashMap <>() {{
        put("token", token);
        put("permissions", permissions);
        put("isLogin", true);
      }};
      this.recordLoginInfo(userId);
      return result;
    }
    return result;
  }
  
  /**
   * 记录登录信息
   *
   * @param userId 用户ID
   */
  @Override
  public void recordLoginInfo(Integer userId) {
    LoginInfoEntity loginInfo = new LoginInfoEntity();
    loginInfo.setUserId(userId);
    loginInfo.setType(1);
    loginInfo.setLoginIp(IpUtils.getIpAddr());
    loginInfoService.save(loginInfo);
  }
  
}
